package com.ma.chapter4.t7;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import static com.ma.util.Sleeper.sleep;

/**
 * @ClassName TestReentrantLock4
 * @Author: mayongqiang
 * @DATE 2022/3/15 19:41
 * @Description: lock.tryLock() 超时失败
 */
@Slf4j(topic = "m.ReentrantLock4")
public class TestReentrantLock4 {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(() -> {
            log.debug("启动");
            try {
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {
                    log.debug("获取等待一秒后失败,返回");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                log.debug("获得了锁");
            } finally {
                lock.unlock();
            }
        }, "t1");
        lock.lock();
        log.debug("获得了锁");
        t1.start();
        sleep(0.5);
        lock.unlock();

    }
}
